<?php

namespace backend\controllers;

use Yii;
use backend\models\Taozhuang;
use backend\models\TaozhuangSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;

use backend\models\Image;
use backend\models\UploadForm;
use backend\models\GrpSpace;
use backend\models\BuildType;
use backend\models\TaozhuangPos;
use yii\web\ForbiddenHttpException;
use backend\models\Brand;
use backend\models\PrfType;
use backend\models\SysImage;

/**
 * TaozhuangController implements the CRUD actions for Taozhuang model.
 */
class TaozhuangNewController extends Controller
{
	const BASE_URL = '/furniture_test/furniture_test.php?';
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'bulk-delete' => ['post'],
                ],
            ],
        ];
    }
	public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('taozhuang') || \Yii::$app->user->can('taozhuang-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all Taozhuang models.
     * @return mixed
     */
    public function actionEdit()
    {    
        if(\Yii::$app->user->can('taozhuang-manage')){
           //查询所有套装
            $tzlist=Taozhuang::find()->select("sid,name")->asArray()->orderBy("top_time desc,sid asc")->all();
            //查询所有使用中品牌
            $brandlist=Brand::find()->where("useing=1")->select("id,name")->asArray()->orderBy("id asc")->all();
            //新套装 
            $newtaozhuang_list2=PrfType::findNewtaozhuangList();
            //秀家
            $xiujia_list2=PrfType::findXiujiaList();  
            //老结构
            $old_list2=PrfType::findOldList();
          
            //分类表
            $cateList=PrfType::findCateList();
            $return_data=['tzlist'=>$tzlist,'brandlist'=>$brandlist,'newtaozhuang_list2'=>$newtaozhuang_list2,'xiujia_list2'=>$xiujia_list2,"old_list2"=>$old_list2,"cateList"=>$cateList];
            return $this->render('edit',$return_data);
        }else{
            throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        }
    }

   /**
    * 根据套装名称模糊查询
    */
    public function actionSearch($tzname){
        if($tzname==""){
            $return_date=array("code"=>0);
            echo json_encode($return_date);exit();
        }else{
            $sql="select sid,name from  taozhuang where name like '%".$tzname."%'";
           $taozhuang=Taozhuang::findBySql($sql)->asArray()->all();
           if(count($taozhuang)>0){
               $return_date=array("code"=>1,"tz"=>$taozhuang,"count"=>count($taozhuang));
               echo json_encode($return_date);exit();
           }else{
               $return_date=array("code"=>2);
               echo json_encode($return_date);exit();
           }
           
        }
        
    }
    /**
     * Displays a single Taozhuang model.
     * @param integer $id
     * @return mixed
     */
     public function actionView($id)
    {   
        $request = Yii::$app->request;
        if($request->isAjax){
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                    'title'=> Yii::t('app', 'Taozhuang'),
                    'content'=>$this->renderPartial('view', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"])/*.
                            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])*/
                ];    
        }else{
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
    }


    /**
     * Creates a new Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $model = new Taozhuang();  

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> "Create new Taozhuang",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
        
                ];         
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'true',
                    'title'=> "Create new Taozhuang",
                    'content'=>'<span class="text-success">Create Taozhuang success</span>',
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Create More',['create'],['class'=>'btn btn-primary','role'=>'modal-remote'])
        
                ];         
            }else{           
                return [
                    'title'=> "Create new Taozhuang",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
        
                ];         
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->sid]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }
       
    }

    /**
     * Updates an existing Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $model = $this->findModel($id);       

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> "Update Taozhuang #".$id,
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
                ];         
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'true',
                    'title'=> "Taozhuang #".$id,
                    'content'=>$this->renderPartial('view', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])
                ];    
            }else{
                 return [
                    'title'=> "Update Taozhuang #".$id,
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
                ];        
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->sid]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    }

    /**
     * Delete an existing Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>true];    
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }


    }

     

    /**
     * Finds the Taozhuang model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Taozhuang the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Taozhuang::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
   /**
    * 根据id查询图片目录的addr
    */
    public function actionSearchAddr($id){
        
        //-1 老结构  -2分类表  
        $prfType=PrfType::findOne($id);
        if($prfType){
            $addr=$prfType->addr;
        }else{
            $addr='';
        }
        
        echo $addr;exit();
    }

    /**
     * 添加分类
     */
    public function actionAddAddr($addr,$typename,$show_img_id,$addold){
         
        //-1 老结构  
        if($show_img_id==-1){
            $sql="select id from prf_type where father=-1 AND typename='$typename' and addr='$addold'";
            $prf_type_list=PrfType::findBySql($sql)->asArray()->all();
            if(count($prf_type_list)>0){
                echo 2;exit();
            }else{
                $prfType=new PrfType();
                $prfType->typename=$typename;
                $prfType->addr=$addold;
                $prfType->father=-1;
                $result=$prfType->save();
                echo $result;exit();
            }
        //-2分类表  
        }elseif($show_img_id==-2){
           /*  $sql="select id from prf_type where father=0 AND typename='$typename' and addr is null";
            $prf_type_list=PrfType::findBySql($sql)->asArray()->all();
            if(count($prf_type_list)>0){
                echo 2;exit();
            }else{
                echo "添加素具";
                $prfType=new PrfType();
                $prfType->typename=$typename;
                $prfType->father=0;
                $prfType->addr=" ";
                $result=$prfType->save();
                print_R($prfType);
                echo $result;exit();
            } */
        }else{
            $pos=strpos($addr, "/");
            $str_len=strlen($addr);
            $str_last=substr($addr, $pos+1,$str_len-$pos);
            $addr=$str_last;
            
            $sql="SELECT * FROM prf_type WHERE father=-1 AND typename='$typename'  AND addr='$addr'";
            $prf_type_list=PrfType::findBySql($sql)->asArray()->all();
            if(count($prf_type_list)>0){
                echo 2;exit();
            }else{
                $prfType=new PrfType();
                $prfType->typename=$typename;
                $prfType->addr=$addr;
                $prfType->father=-1;
                $result=$prfType->save();
                echo $result;exit();
            }
            
        }
        
        
     }
     
     /**
      * 删除分类
      * 
      */
     public function actionDelAddr($id){
         //查询当前是否存在图片或者下级是否存在图片，如果存在不可以删除
         $prfType=PrfType::findOne($id);
         if($prfType){
             $father=$prfType->father;
             //老结构
             if($father<=0){
                 $addr=$prfType->addr;
                 $sql="  SELECT id FROM sys_image WHERE TYPE IN (SELECT id FROM prf_type WHERE addr LIKE '$addr/%') OR TYPE =$id LIMIT 1";
                 $prfTypeList=SysImage::findBySql($sql)->asArray()->all();
                 if(count($prfTypeList)>0){
                     //存在图片不可以删除
                     echo 2;exit();
                 }else{
                     $sql=" DELETE FROM prf_type WHERE  addr LIKE '$addr/%' OR id=$id";
                     $result=Yii::$app->db->createCommand($sql)->execute();
                     echo $result;exit();
                 }
                 //新结构
             }else{
                 $sql="SELECT id FROM sys_image WHERE TYPE IN ( SELECT id FROM prf_type WHERE father IN(SELECT id FROM prf_type WHERE father=$id) OR father=$id) LIMIT 1";
                 $prfTypeList=SysImage::findBySql($sql)->asArray()->all();
                 if(count($prfTypeList)>0){
                     //存在图片不可以删除
                     echo 2;exit();
                 }else{
                     $sql="DELETE FROM prf_type WHERE id=$id OR father=$id OR father IN (SELECT id FROM prf_type WHERE father=$id )";
                     $result=Yii::$app->db->createCommand($sql)->execute();
                     echo $result;exit();
                 }
             }
             
         }else{
             echo 2;exit();
         }
       
         
     }
   /**
    * (non-PHPdoc)
    * @see \yii\base\Controller::actions()
    * by suiyue
    */
   public function actions(){
   	return [
   			'upload'=>[
   					'class'=>'backend\widgets\ueditor\UEditorAction',
   					'config'=>[
   							//  /gjj/backend/web/images/
   								'imageUrlPrefix'=>"https://".$_SERVER['SERVER_NAME']."/gjj/backend/web/images/",//图片访问路径前缀
			   					'imagePathFormat'=>'{rand:2}/{time}{rand:6}',
			   				    'imageRoot'=>\Yii::getAlias("images")
   					]
   			]
   	];
   	
   }
   /**
    * vr编辑
    * by skt 2019-2-18
    */
   public function actionVrEdit(){
    $model = new UploadForm();
    $model->scenario = 'upload_img';
    return $this->render('vr_edit', [
           'model' => $model, 
    ]);
   }
}
